<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>02_防抖-防抖基本实现</title>
</head>

<body>

  <input type="text">

  <script>

    function debounce(fn, delay) {
      let timer = null;
      return function () {
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          fn()
          timer = null // 清空timer，防止内存泄漏
        }, delay)
      }
    }

    // 3.防抖处理代码
    let counter = 1
    const inputEl = document.querySelector('input')
    inputEl.oninput = debounce(function () {
      console.log(`发送网络请求${counter++}:`, this.value)
    }, 1000)

  </script>

</body>

</html>